var adminRoleCtrl = myApp.controller('adminRoleCtrl', ['$scope', '$rootScope', 'NgTableParams', function($scope, $rootScope, NgTableParams) {
	$rootScope.firstType = Tools.permissionList[5].permissionId;
	$rootScope.secondType = Tools.permissionList[5].sonPermission[0].permissionId;

	$scope.newRoleItem = {};
	$scope.modRoleItem = {};
	$scope.delRoleItem = {};
	$scope.sex = Tools.sex;
	// 分页 
	$scope.pageList = [];
	$scope.curPage = 1;
	$scope.totalPage = 1;
	$scope.totalRow = 0;
	var PAGESIZE = 10;

	// 提示弹层
	$scope.msg = "";
	$scope.visible = false;

	$scope.range = function(n) {
		return new Array(n);
	};

	$scope.getAllUserList = function() {
		var data = {};
		commonSrv.getAllUserList(data, function(result) {
			$scope.userList = result.data;
		}, function(result) {
			console.log("获取失败");
		}, function() {
			$scope.$apply();
		});
	};

	/**
	 * 获取用户信息列表
	 * @param  {[Object]} data [参数]
	 * @return {[type]}      [description]
	 */
	$scope.getRoleList = function(curPage) {
		// console.log("请求第"+curPage+"页");
		var data = {
			curPage: curPage,
			pagesize: PAGESIZE
		};
		commonSrv.getRoleList(data, function(result) {
			var list = result.data;
			$scope.roleList = new NgTableParams({count: PAGESIZE}, { counts: [],  dataset: list});
			// 分页
			var paginate = result.paginate;
			$scope.totalPage = paginate.totalPage;
			$scope.totalRow = paginate.totalRow;
			$scope.setPage(curPage);
		}, function(result) {
			console.log("获取失败");
		}, function() {
			$scope.$apply();
		});
	};

	// 设置分页
	$scope.setPage = function(curPage) {
		var newPageList = [];
		if (curPage < 1 || curPage > $scope.totalPage) {
			alert("设置分页失败");
			return;
		}
		var SHOWSIZE = 5;
		// 总页数小于SHOWSIZE
		if($scope.totalPage <= SHOWSIZE) {
			for(var i=0; i<$scope.totalPage; i++) {
				newPageList.push(i+1);
			}
		// 总页数大于等于SHOWSIZE
		} else {
			if(curPage > 2) {
				// 最后5页
				if(($scope.totalPage - curPage) < 2) {
					for(var i = ($scope.totalPage - 5); i < $scope.totalPage; i++) {
						newPageList.push(i + 1);
					}
				} else {
					for (var i = (curPage - 3); i < ((curPage + 2) > $scope.totalPage ? $scope.totalPage : (curPage + 2)); i++) {
                        newPageList.push(i + 1);
                    }
				}
			} else {
				for(var i=0; i<SHOWSIZE; i++) {
					newPageList.push(i + 1);
				}
			}
		}
        $scope.pageList = newPageList;
        $scope.curPage = curPage;
	};

	//设置当前选中页样式
    $scope.isActivePage = function (page) {
        return $scope.curPage == page;
    };
    //上一页
    $scope.previous = function () {
        if($scope.curPage > 1) {
        	$scope.getRoleList($scope.curPage - 1);
        }
    }
    //下一页
    $scope.next = function () {
        if($scope.curPage < $scope.totalPage) {
        	$scope.getRoleList($scope.curPage + 1);
        }
    };

	// 新增
	/**
	 * 打开新增用户信息面板
	 * @return {[type]} [description]
	 */
	$scope.openAdd = function() {
		$scope.newRoleItem = {
			name: '',
			description: '',
			permissionIds: [],
			permissionList: angular.copy(Tools.permissionList),
			userIds: '',
			userList: [],
			warn: {
				name: ""
			}
		};
		$("#addRoleModel").modal({backdrop: 'static', keyboard: false, show: true});
	};

	/**
	 * 新增角色
	 * @param {[type]} item [description]
	 */
	$scope.addRole = function() {
		// 1.角色名称 
		$scope.watchName('new');
		// 2.角色描述

		// 3.角色权限
		var permissionIds = '';
		// 选中个数
		var count = 0;
		// 只传有开放权限的id
		var array = $scope.newRoleItem.permissionList;
		for(var i=0; i<array.length; i++) {
			for(var j=0; j<array[i].sonPermission.length; j++) {
				if(array[i].sonPermission[j].check) {
					permissionIds += array[i].sonPermission[j].permissionId + ',';
					count++;
				}
			}
		}
		// 去除最后一个逗号
		if(count >= 1) {
			permissionIds=permissionIds.substring(0, permissionIds.length-1);	
		}
		
		// 4.角色用户
		var userIds = '';
		var userArray = $scope.newRoleItem.userList;
		for (var i in userArray) {
			if(i != (userArray.length - 1) ) {
				userIds += userArray[i].userId+',';
			} else {
				userIds += userArray[i].userId;
			}
		}
		// 判断是否可以提交
		if(!Tools.reg.isNull($scope.newRoleItem.warn.name)) {
			alert("请修改表单");
			return;
		}
		var data = {
			name: $scope.newRoleItem.name,
			description: $scope.newRoleItem.description,
			permissionIds: permissionIds,
			userIds: userIds
		};
		commonSrv.addRole(data, function(result) {
			if(result.status == 0) {
				$scope.msg = "新增成功";
				$scope.visible = true;					
				$scope.getRoleList(1);
				$scope.newRoleItem = {};
				$("#addRoleModel").modal('hide');
			}
		}, function(result) {
			// 新增角色失败
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};

	// 删除
	/**
	 * 打开删除角色信息面板
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.openDel = function(item) {
		$scope.delRoleItem = item;
		$('#delRoleModel').modal('show');
	};
	/**
	 * 删除角色
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.delRole = function() {
		var data = {
			userroleId: $scope.delRoleItem.userroleId
		};
		commonSrv.delRole(data, function(result) {
			if(result.status == 0) {
				$scope.msg = "删除角色成功";
				$scope.visible = true;
				$scope.getRoleList($scope.curPage);
				$("#delRoleModel").modal('hide');
				$scope.delRoleItem = {};
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};

	// 修改
	/**
	 * 打开修改角色信息面板
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.openEdit = function(item) {
		$scope.getRoleById(item.userroleId, function(result) {
			$scope.modRoleItem = result.data;
			// 权限列表
			$scope.modRoleItem.permissionList = angular.copy(Tools.permissionList);
			var permissionIds = $scope.modRoleItem.permissionIds.split(",");
			for(var i=0; i<$scope.modRoleItem.permissionList.length; i++) {
				for(var j=0; j<$scope.modRoleItem.permissionList[i].sonPermission.length; j++) {
					for(var k=0; k<permissionIds.length; k++) {
						if(permissionIds[k] == $scope.modRoleItem.permissionList[i].sonPermission[j].permissionId) {
							$scope.modRoleItem.permissionList[i].sonPermission[j].check = true;
						}
					}
				}
			}
			// 用户列表
			if($scope.modRoleItem.userList == null || $scope.modRoleItem.userList == undefined) {
				$scope.modRoleItem.userList = [];
			} else {
				var temp = new Array();
				// 用户列表
				for(var i=0; i<$scope.modRoleItem.userList.length; i++) {
					for(var j=0; j<$scope.userList.length; j++) {
						if($scope.modRoleItem.userList[i].userId == $scope.userList[j].userId) {
							temp.push($scope.userList[j]);
						}
					}
				}
			}
			$scope.modRoleItem.userList = temp;
			$scope.modRoleItem.warn = {
				name: ""
			};
			$("#editRoleModel").modal({backdrop: 'static', keyboard: false, show: true});
		});

	};
	/**
	 * 修改角色
	 * @param  {[type]} item [description]
	 * @return {[type]}      [description]
	 */
	$scope.editRole = function() {
		// 1.角色名
		$scope.watchName('edit');

		// 2.权限列表
		var permissionIds = '';
		var userIds = '';
		// 选中个数
		var count = 0;
		// 权限列表
		// 只传有开放权限的id
		var array = $scope.modRoleItem.permissionList;
		for(var i=0; i<array.length; i++) {
			for(var j=0; j<array[i].sonPermission.length; j++) {
				if(array[i].sonPermission[j].check) {
					permissionIds += array[i].sonPermission[j].permissionId + ',';
					count++;
				}
			}
		}
		// 去除最后一个逗号
		if(count >= 1) {
			permissionIds=permissionIds.substring(0, permissionIds.length-1);	
		}

		// 用户列表
		var userList = $scope.modRoleItem.userList;
		for(var i=0; i<userList.length; i++) {
			if(i != userList.length -1) {
				userIds += userList[i].userId + ',';
			} else {
				userIds += userList[i].userId;
			}
		}

		// 判断是否可以提交
		if(!Tools.reg.isNull($scope.modRoleItem.warn.name)) {
			alert("请修改表单");
			return;
		}
		var data = {
			name: $scope.modRoleItem.name,
			description: $scope.modRoleItem.description,
			userroleId: $scope.modRoleItem.userroleId,
			permissionIds: permissionIds,
			userIds: userIds
		};
		commonSrv.editRole(data, function(result) {
			if(result.status == 0) {
				$scope.msg = "修改角色信息成功";
				$scope.visible = true;
				$scope.getRoleList($scope.curPage);
				$("#editRoleModel").modal('hide');
				$scope.modRoleItem = {};
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}
		}, function() {
			$scope.$apply();
		});
	};
	/**
	 * 获取单个角色信息
	 * @param  {[type]}   id [description]
	 * @param  {Function} cb [description]
	 * @return {[type]}      [description]
	 */
	$scope.getRoleById = function (id, cb) {
		var data = {
			userroleId: id
		};
		commonSrv.getRoleById(data, function(result) {
			if(result.status == 0) {
				cb(result);
			} else {
				alert("获取角色信息失败");
			}
		}, function(result) {
			if(result.status == 1) {
				alert(result.msg);
			}		
		}, function() {
			$scope.$apply();
		});
	};

	// 验证
	// 1.角色名--不能为空，4-20中文
	$scope.watchName = function (type) {
		var nullWarn = "角色名不能为空";
		var formatWarn = "请输入长度为4-20的中文角色名";
		if(type == 'new') {
			if(Tools.reg.isNull($scope.newRoleItem.name)) {
				$scope.newRoleItem.warn.name = nullWarn;
			} else {
				if(!Tools.reg.roleName($scope.newRoleItem.name)) {
					$scope.newRoleItem.warn.name = formatWarn;
				} else {
					$scope.newRoleItem.warn.name = "";
				}
			}
		} else if(type == 'edit') {
			if(Tools.reg.isNull($scope.modRoleItem.name)) {
				$scope.modRoleItem.warn.name = nullWarn;
			} else {
				if(!Tools.reg.roleName($scope.modRoleItem.name)) {
					$scope.modRoleItem.warn.name = formatWarn;
				} else {
					$scope.modRoleItem.warn.name = "";
				}
			}
		}
	};
	// 初始化
	function init() {
		$scope.getRoleList($scope.curPage);
		$scope.getAllUserList();
		$(document).ready(function() {

		});
	}
	init();
}]);